#include "RealTimeData.h"
#include "MyMqttClient.h"
#include <unistd.h>
#include "stdio.h"

// 测试 mqtt publish 实时数组
static bool is_connect = false;
static bool is_can_send = 0;
static int sub_ok_cnt = 0;
static void on_connect(void *myclient, MyMqttClientMessage *m, MyMqttClientEvent event)
{
    MyMqttClient *cli = (MyMqttClient *)myclient;
    printf("on_connect..\r\n");
    is_connect = true;
}

static void on_sub(void *myclient, MyMqttClientMessage *m, MyMqttClientEvent event)
{
    sub_ok_cnt++;
    if (sub_ok_cnt >= 3)
        is_can_send = true;
}
static void on_pub(void *myclient, MyMqttClientMessage *m, MyMqttClientEvent event)
{
    std::cout << ">>>>>on pub: topic = " << std::string(m->pub_topic) << std::endl;
    std::cout << ">>>>>on pub: event = " << event << std::endl;
    std::cout << ">>>>>payload = " << std::string((const char *)m->message.payload) << std::endl;
}
void on_recv(void *myclient, MyMqttClientMessage *m, MyMqttClientEvent event)
{
    printf("on_recv:message=  %s\r\n", (char *)(m->message.payload));
}
void test_mqtt_publish(void)
{
    // std::string devicename = "0x0161304370";
    // long deviceid = 0x0161304370;
    // char*key = (char*)"23048f58";

    std::string devicename = "01608B0240";
    long deviceid = 0x01608B0240;
    char*key = (char*)"e567b535";

    int seconds = 0;
    MyMqttClient mq;
    mq.on_connect = on_connect;
    mq.on_sub = on_sub;
    mq.on_recv = on_recv;
    mq.on_pub = on_pub;
    mq.init_params(deviceid, key, (char *)"mqtt://58.42.237.171:1883");
    if (mq.connect() >= 0)
    {
        while (1)
        {
            mq.poll();
            usleep(10000);
            if (is_can_send)
            {
                std::cout << "开始发送数据" << std::endl;
                is_can_send = false;
                RealTimeDataItemJson rj;
                //rj.tm = 1722861842; // time((time_t*)0);
                sql::time t = sql::time::now();
                rj.tm = t.get();
                rj.ch = 2;
                rj.stcd = devicename;

                RealTimeData rt;
                //rt.to_inv_solar(rj.values);
                //rt.to_sms(2,rj.values);
                //rt.to_ib(rj.values);
                //rt.to_yu(rj.values);
                rt.to_duanluqi(rj.values);
                string str = Json::class2jsonstring(rj);
                std::cout << "publish:" << str << std::endl;
                mq.pub(mq.mp.pub_realtime, (char *)str.c_str(), str.size());
            }
        }
    }
}